package com.chengzhi.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @author ruanchengzhi
 * @description: customgatewayfilter
 * @date 2019/9/30 11:30
 */
public class CustomGateWayFilter implements GatewayFilter, Ordered {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static String STARTTIME = "statTime";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(STARTTIME, System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            Long startTime = exchange.getAttribute(STARTTIME);
            long endTime = System.currentTimeMillis();
            if (Objects.nonNull(startTime)) {
                logger.info("--execute time [{}]", (endTime - startTime));
            }
        }));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
